/**数据验证*/
var AnmeterValidator = function() {  
    var handleSubmit = function() { 
        $('.form-horizontal').validate({  
            errorElement : 'span',  
            errorClass : 'help-block',  
            focusInvalid : false,  
            rules : {  
            	"snum" : {  
                    required : true  
                },
                "start":{  
                    required : true,
                    number:true
                }
            },  
            messages : {  
            	"snum"  : {  
                    required : "请输入表号."  
                },
                "start":{  
                    required : "请输入起始读数",
                    number:"请输入数字"
                }
            },  
  
            highlight : function(element) { 
                $(element).closest('.control-group').addClass('error');  
            },  
  
            success : function(label) { 
                label.closest('.control-group').removeClass('error');  
                label.remove();
            },  
  
            errorPlacement : function(error, element) {  
            	element.parent('div').append(error);  
            },  
  
            submitHandler : function(form) {
                form.submit();
            }  
        });  
  
        $('.form-horizontal input').keypress(function(e) {  
            if (e.which == 13) {  
                if ($('.form-horizontal').validate().form()) {  
                    $('.form-horizontal').submit();  
                }  
                return false;  
            }  
        });  
    }  
    return {  
        init : function() { 
            handleSubmit(); 
        }  
    };  
  
}();
var setting = {
	check: {
		enable: true,
		chkStyle: "radio",
		radioType: "all"
	},
	async: {
		enable: true,
		url: getUrl
	},
	data: {
		simpleData: {
		  enable: true
	    }
	},
	view: {
		expandSpeed: ""
	},
	callback: {
		beforeExpand: beforeExpand,
		onAsyncSuccess: onAsyncSuccess,
		onAsyncError: onAsyncError
	}
};
function getUrl(treeId, treeNode) {
	var sign=treeNode.id.substr(0,1);
	var cid=treeNode.id.substr(1);
	if(sign=='C'){
		return "../base/queryTree_Ban.action?cid="+cid+"&urlSign=anmeterChose";
	}else if(sign=="B"){
		return "../base/queryTree_Unit.action?bid="+cid+"&urlSign=anmeterChose";
	}else if(sign=="U"){
		return "../base/queryTree_Room.action?uid="+cid+"&urlSign=anmeterChose";
	}
};
function beforeExpand(treeId, treeNode) {
	if (!treeNode.isAjaxing) {
		ajaxGetNodes(treeNode, "refresh");
		return true;
	} else {
		alert("正在下载数据中，请稍后展开节点。。。");
		return false;
	}
};
function ajaxGetNodes(treeNode, reloadType) {
	var zTree = $.fn.zTree.getZTreeObj("menup");
	if (reloadType == "refresh") {
		treeNode.icon = "../script/ztree/css/zTreeStyle/img/loading.gif";
		zTree.updateNode(treeNode);
	}
	zTree.reAsyncChildNodes(treeNode, reloadType, true);
};
function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
	var zTree = $.fn.zTree.getZTreeObj("menup");
	alert("异步获取数据出现异常。");
	treeNode.icon = "";
	zTree.updateNode(treeNode);
};
function onAsyncSuccess(event, treeId, treeNode, msg) {
	var zTree = $.fn.zTree.getZTreeObj("menup"),
	totalCount = treeNode.count;
	treeNode.icon = "";
	zTree.updateNode(treeNode);
	zTree.selectNode(treeNode.children[0]);
};

$(document).ready(function(){
	$.post("../base/query_RoomInfo.action",{"urlSign":"anmeterChose"},function(result){
		$.fn.zTree.init($("#menup"), setting, result.communitys);
	});
	AnmeterValidator.init();
	
});
function addTr2(tab, row){
   $("#myroominfo").modal('show');
};
function addTr(tab, row, trHtml){
    //获取table最后一行 $("#tab tr:last")
    //获取table第一行 $("#tab tr").eq(0)
    //获取table倒数第二行 $("#tab tr").eq(-2)
    var $tr=$("#"+tab+" tr:last");
    if($tr.size()==0){
       alert("指定的table id或行数不存在！");
       return;
    }
    $tr.after(trHtml);
 };
function chose(tab,row){
   var treeObj = $.fn.zTree.getZTreeObj("menup");
   var sNodes = treeObj.getCheckedNodes(true);
   var id="";
   if(sNodes.length>0){
		id=sNodes[0].id;
   }else{
	    return;
   }
   $.post("../dashboard/loadResidents_Anmeter.action",{"rid":id},function(result){
	   if(result.residentsex.length<=0){
		   alert("该房间暂无住户信息，所以不能添加!");
		   return;
	   }
	   for(var i=0;i<result.residentsex.length;i++){
	   var trHtml="<tr><td><input type='checkbox' id='inlineCheckbox1'  name='ckb' value='"+($("#dynamictable").find("tr").length)+"'></td><td>"+
	   "<input class='input-xlarge focused' disabled id='roomrcode' name='roomrcode' type='text' value='"+result.residentsex[i].room.rcode+"("+result.residentsex[i].room.unit.ban.community.cname+result.residentsex[i].room.unit.ban.bname+result.residentsex[i].room.unit.uname+")"+"'></td>"+
	   "<td class='center'>" +
	   "<input class='input-small focused' id='rcode' name='rcode' type='hidden' value='"+result.residentsex[i].rcode+"'>" +
	   "<input class='input-small focused' id='rid' name='rid' type='hidden' value='"+result.residentsex[i].room.rid+"'>" +
	   "<input class='input-small focused' disabled id='rname' name='rname' type='text' value='"+result.residentsex[i].rname+"'></td>"+
	   "<td class='center'><input class='input-small focused' disabled id='rnum' name='rnum' type='text' value='"+result.residentsex[i].rnum+"'></td>"+
	   "<td class='center'><input class='input-small focused' id='compare' name='compare' type='text' value=''></td>"+
	   "<td class='center'><input class='input-small focused' id='content' name='content' type='text' value=''></td></tr>";
       addTr(tab, row, trHtml);
	   }
	   /*计算分摊*/
	   share();
       $("#myroominfo").modal('hide');
   });
};
/*计算分摊*/
function share(){
	var sid=$("select[name=sid]").val();
	if(sid=="001"){//无需分摊
		$("#dynamictable").find("tr").each(function(i,trobj){
		    if(i>0){
			   $(trobj).find("input[name=compare]").eq(0).val(1);
			}
		 });
	}else if(sid=="002"){//按户分摊
		var tmp=0;
		var count=0;
		var rows=$("#dynamictable").find("tr").length-1;
		$("#dynamictable").find("tr").each(function(i,trobj){
		    if(i>0 && i<rows){
		    	tmp=changeTwoDecimal_f(1/rows);
		    	count=parseFloat(count,10)+parseFloat(tmp,10);
			   $(trobj).find("input[name=compare]").eq(0).val(tmp);
			}else if(i==rows){
			   $(trobj).find("input[name=compare]").eq(0).val(changeTwoDecimal_f(1-count));
			}
		 });
	}else if(sid=="003"){//按人数分摊
		var pnum=0;
		$("#dynamictable").find("tr").each(function(i,trobj){
		    if(i>0){
		       var tmp=$(trobj).find("input[name=rnum]").eq(0).val();
		       if(tmp!=null && tmp!=""){
			      pnum=pnum+parseInt(tmp,10);
		       }
			}
		 });
		var tmp=0;
		var count=0;
		var rows=$("#dynamictable").find("tr").length-1;
		$("#dynamictable").find("tr").each(function(i,trobj){
		    if(i>0 && i<rows){
		    	var cpnum=$(trobj).find("input[name=rnum]").eq(0).val();
		    	tmp=changeTwoDecimal_f(cpnum/pnum);
		    	count=parseFloat(count,10)+parseFloat(tmp,10);
			   $(trobj).find("input[name=compare]").eq(0).val(tmp);
			}else if(i==rows){
			   $(trobj).find("input[name=compare]").eq(0).val(changeTwoDecimal_f(1-count));
			}
		 });
	}
}
function delTr(ckb){
    //获取选中的复选框，然后循环遍历删除
    var ckbs=$("input[name="+ckb+"]:checked");
    if(ckbs.size()==0){
       alert("要删除指定行，需选中要删除的行！");
       return;
    }
	 var i=0;
    ckbs.each(function(i,ckb){
		$("#dynamictable tr").eq($(ckb).val()-i).remove();
		i++;
    });
 };
 function delTr2(){
	 // alert($("#dynamictable").find("tr").length);
	 delTr('ckb');
	$("#dynamictable").find("tr").each(function(i,trobj){
		if(i>0){
			$(trobj).find("td").eq(0).find("input").eq(0).val(i);
		}
	});
	/*计算分摊*/
    share();
};
/**保存数据*/
function saveAnmeter(){
	  	$('#myModal').modal('show');
	  	//电表信息
	  	var acode=$("#acode").val();
	  	var snum=$("#snum").val();
	  	var company=$("#company").val();
	  	var type=$("#type").val();
	  	var cycle=$("#cycle").val();
	  	var record=$("#record").val();
	  	var start=$("#start").val();
	  	var sid=$("select[name=sid]").val();
	  	var pid=$("select[name=pid]").val();
	  	
	  	//管户信息
	  	var rcodeobjs=$("input[name=rcode]");
	  	var ridobjs=$("input[name=rid]");
	  	var rnameobjs=$("input[name=rname]");
	  	var rnumobjs=$("input[name=rnum]");
	  	var compareobjs=$("input[name=compare]");
	  	var contentobjs=$("input[name=content]");
	  	var roomrcodeobjs=$("input[name=roomrcode]");
	  	var rcodes='';
	  	var rids='';
	  	var rnames='';
	  	var rnums='';
	  	var compares='';
	  	var contents='';
	  	var roomcodes='';
	  	if(rcodeobjs==undefined || rcodeobjs==null || rcodeobjs.length<=0){
	  		$('#myModal').modal('hide');
	  		alert("电表至少要有一个被管住户，否则不能保存。");
	  		return;
	  	}
	  	for(var i=0;i<rcodeobjs.length;i++){
	  		rcodes=rcodes+$(rcodeobjs[i]).val()+',';
	  		rids=rids+$(ridobjs[i]).val()+',';
	  		rnames=rnames+$(rnameobjs[i]).val()+',';
	  		rnums=rnums+$(rnumobjs[i]).val()+',';
	  		compares=compares+$(compareobjs[i]).val()+',';
	  		contents=contents+$(contentobjs[i]).val()+',';
	  		roomcodes=roomcodes+$(roomrcodeobjs[i]).val()+',';
	  	}
	  	$.post("../dashboard/save_Anmeter.action",{"anmeter.acode":acode,"anmeter.snum":snum,"anmeter.company":company,"anmeter.start":start,
	  		"anmeter.record":record,"anmeter.type":type,"anmeter.cycle":cycle,"anmeter.spread.sid":sid,"anmeter.readPerson.pid":pid,"rcodes":rcodes,"rids":rids,
	  		"rnames":rnames,"rnums":rnums,"compares":compares,"contents":contents,"roomcodes":roomcodes
	  		}, function(result) {
	  		if(result.msg=="succ"){
	  			$('#myModal').modal('hide');
	  			$("#alertinfo").html("电表信息维护成功");
	  			$('#myinfo').modal('show');
	  			$("#closewin").bind("click",function(){
					window.location.href="../dashboard/init_Anmeter.action";
				});
	  		}else{
	  			$('#myModal').modal('hide');
	  			$("#alertinfo").html(result.msg);
	  			$('#myinfo').modal('show');
	  		}
	  	});
};